package com.insight.modules.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.PermissionData;
import com.insight.common.system.query.QueryGenerator;
import com.insight.common.util.oConvertUtils;
import com.insight.modules.system.entity.SysTenant;
import com.insight.modules.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * 租户配置信息
 */
@Slf4j
@RestController
@RequestMapping("/sys/tenant")
public class SysTenantController {

    @Autowired
    private ISysTenantService sysTenantService;

    /**
     * 分页查询租户列表数据
     * 支持条件筛选，分页参数，权限数据过滤注解
     * @param sysTenant  查询条件封装对象
     * @param pageNo     当前页码，默认1
     * @param pageSize   每页显示条数，默认10
     * @param req        请求对象，用于获取请求参数
     * @return           分页查询结果封装对象，包含租户列表和分页信息
     */
    @PermissionData(pageComponent = "system/TenantList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Result<IPage<SysTenant>> queryPageList(SysTenant sysTenant,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {

        Result<IPage<SysTenant>> result = new Result<>();

        // 初始化查询条件封装器，自动根据sysTenant对象和请求参数生成QueryWrapper
        QueryWrapper<SysTenant> queryWrapper = QueryGenerator.initQueryWrapper(sysTenant, req.getParameterMap());

        // 创建分页对象
        Page<SysTenant> page = new Page<>(pageNo, pageSize);

        // 执行分页查询
        IPage<SysTenant> pageList = sysTenantService.page(page, queryWrapper);

        // 封装查询结果
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 新增租户信息
     * @param sysTenant 租户实体对象，来自请求体JSON
     * @return          处理结果，包括是否成功及提示信息
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result<SysTenant> add(@RequestBody SysTenant sysTenant) {
        Result<SysTenant> result = new Result<>();

        if (sysTenant == null || sysTenant.getId() == null) {
            return result.error500("租户ID不能为空");
        }

        try {
            if (sysTenantService == null) {
                return result.error500("服务不可用");
            }
            if (sysTenantService.getById(sysTenant.getId()) != null) {
                return result.error500("该编号已存在!");
            }
            sysTenantService.save(sysTenant);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑更新租户信息
     * @param tenant 包含修改内容的租户实体对象
     * @return       处理结果，是否成功及提示信息
     */
    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public Result<SysTenant> edit(@RequestBody SysTenant tenant) {
        Result<SysTenant> result = new Result<>();

        // 根据ID查询原始实体
        SysTenant sysTenant = sysTenantService.getById(tenant.getId());
        if (sysTenant == null) {
            result.error500("未找到对应实体");
        } else {
            // 更新实体信息
            boolean ok = sysTenantService.updateById(tenant);
            if (ok) {
                result.success("修改成功!");
            }
        }
        return result;
    }

    /**
     * 根据ID删除单个租户
     * @param id 租户ID
     * @return   操作结果
     */
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        sysTenantService.removeById(id);
        return Result.ok("删除成功");
    }

    /**
     * 批量删除租户
     * @param ids 多个租户ID，逗号分隔
     * @return    操作结果
     */
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<?> result = new Result<>();
        if (oConvertUtils.isEmpty(ids)) {
            result.error500("未选中租户！");
        } else {
            List<String> ls = Arrays.asList(ids.split(","));
            sysTenantService.removeByIds(ls);
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 根据ID查询单个租户详情
     * @param id 租户ID
     * @return   查询结果及租户数据
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public Result<SysTenant> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<SysTenant> result = new Result<>();
        SysTenant sysTenant = sysTenantService.getById(id);
        if (sysTenant == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(sysTenant);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 查询所有有效的租户列表，可根据ID筛选
     * @param ids 可选，多个租户ID逗号分隔，用于筛选
     * @return    有效租户列表
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    public Result<List<SysTenant>> queryList(@RequestParam(name = "ids", required = false) String ids) {
        Result<List<SysTenant>> result = new Result<>();

        LambdaQueryWrapper<SysTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysTenant::getStatus, 1); // 只查询状态为1的有效租户

        if (oConvertUtils.isNotEmpty(ids)) {
            query.in(SysTenant::getId, ids.split(","));
        }

        // 查询列表（忽略时间等其他条件）
        List<SysTenant> ls = sysTenantService.list(query);

        result.setSuccess(true);
        result.setResult(ls);
        return result;
    }
}

